//
//  ZCMineViewController.m
//  kangbs
//
//  Created by 高睿婕 on 2018/8/14.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCMineViewController.h"
#import "ZCMineTableHeaderView.h"
#import "ZCMineStoreTableViewCell.h"
#import "ZCMineChangePasswordViewController.h"
#import "ZCMineAccountViewController.h"
#import "ZCUserInfoModel.h"

static NSString *storeCellID = @"ZCMineStoreTableViewCell";

@interface ZCMineViewController ()<UITableViewDelegate, UITableViewDataSource, ZCMineTableHeaderViewDelegate>
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UIImageView *headerImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *levelLabel;

@property (nonatomic, strong) UIView *middleView;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) BOOL spread;
@property (nonatomic, strong) ZCUserInfoModel *userInfoModel;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, assign) BOOL originSpread;
@property (nonatomic, copy) NSString *currentOrigin;
@property (nonatomic, strong) NSIndexPath *index;
@property (nonatomic, copy) NSString *currentStore;
@property (nonatomic, strong) NSIndexPath *storeIndex;

@end

@implementation ZCMineViewController
#pragma mark - 懒加载
- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = [UIColor whiteColor];
    }
    return _topView;
}

- (UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
        _bgImageView.image = [UIImage imageNamed:@"Background"];
        _bgImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgImageViewTap:)];
        [_bgImageView addGestureRecognizer:tap];
    }
    return _bgImageView;
}

- (UIImageView *)headerImageView {
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc] init];
        _headerImageView.image = [UIImage imageNamed:@"headImage"];
        _headerImageView.layer.masksToBounds = YES;
        _headerImageView.layer.cornerRadius = space(95);
        _headerImageView.layer.borderColor = [UIColor whiteColor].CGColor;
        _headerImageView.layer.borderWidth = space(4);
    }
    return _headerImageView;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.textColor = [UIColor whiteColor];
        _nameLabel.font = [UIFont systemFontOfSize:FontSize(32)];
    }
    return _nameLabel;
}

- (UILabel *)levelLabel {
    if (!_levelLabel) {
        _levelLabel = [[UILabel alloc] init];
        _levelLabel.textColor = ZCColor(0xffffff, 0.7);
        _levelLabel.font = [UIFont systemFontOfSize:FontSize(26)];
        _levelLabel.text = @"积分";
    }
    return _levelLabel;
}

- (UIView *)middleView {
    if (!_middleView) {
        _middleView = [[UIView alloc] init];
        _middleView.backgroundColor = [UIColor whiteColor];
    }
    return _middleView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 100) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCMineStoreTableViewCell class] forCellReuseIdentifier:storeCellID];
        
    }
    return _tableView;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = ZCColor(0xf5f9fd, 1);
    [self.view addSubview:self.topView];
    [self.topView addSubview:self.bgImageView];
    [self.topView addSubview:self.headerImageView];
    [self.topView addSubview:self.nameLabel];
    [self.topView addSubview:self.levelLabel];
    
    [self.view addSubview:self.middleView];
    [self.middleView addSubview:self.tableView];
    
    [self updateViewConstraints];
    self.spread = NO;
    NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:UserMobile];
    self.nameLabel.text = name;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    self.originSpread = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    [self loadData];}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

#pragma mark - 网络请求
- (void)loadData {
    __weak typeof(self)weakSelf = self;
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool updateBaseURL:hostURL];
        [ZCHttpTool getWithURL:UserInfo params:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                [weakSelf.hud hideAnimated:YES];
                NSDictionary *dataDic = responseObject[@"data"];
                weakSelf.userInfoModel = [[ZCUserInfoModel alloc] init];
                weakSelf.userInfoModel = [ZCUserInfoModel yy_modelWithDictionary:dataDic];
                [weakSelf.tableView reloadData];
                if (weakSelf.currentOrigin) {
                    [weakSelf.tableView selectRowAtIndexPath:weakSelf.index animated:YES scrollPosition:UITableViewScrollPositionNone];
                }
                weakSelf.currentStore = [[NSUserDefaults standardUserDefaults] objectForKey:UserStoreName];
                weakSelf.storeIndex = [NSIndexPath indexPathForRow:0 inSection:0];
                [weakSelf.tableView selectRowAtIndexPath:weakSelf.storeIndex animated:YES scrollPosition:UITableViewScrollPositionNone];

            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - 跳转账号管理
- (void)bgImageViewTap:(UITapGestureRecognizer *)tap {
    ZCMineAccountViewController *accountVC = [[ZCMineAccountViewController alloc] init];
    [self.navigationController pushViewController:accountVC animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        if (self.spread) {
            return self.userInfoModel.storehouses.count;
        }
    }else if (section == 1) {
        if (self.originSpread) {
            return self.userInfoModel.opDeliveryPoints.count + 1;
        }
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 || indexPath.section == 1) {
        ZCMineStoreTableViewCell *storeCell = [tableView dequeueReusableCellWithIdentifier:storeCellID forIndexPath:indexPath];
        storeCell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.section == 0) {
            ZCUserInfoStoreModel *storeModel = self.userInfoModel.storehouses[indexPath.row];
            storeCell.store = storeModel.name;
        }else if (indexPath.section == 1) {
            if (indexPath.row == 0) {
                storeCell.store = @"全部";
            }else {
                ZCOriginLocationModel *originModel = self.userInfoModel.opDeliveryPoints[indexPath.row - 1];
                storeCell.store = originModel.name;
            }
        }
        return storeCell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(90);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(90);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    ZCMineTableHeaderView *headerView = [[ZCMineTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, space(90))];
    headerView.delegate = self;
    headerView.index = section;
    if (section == 0) {
        headerView.title = @"仓库";
        headerView.isLine = YES;
        headerView.desc = self.currentStore;
        headerView.image = [UIImage imageNamed:@"mine_store"];
    }else if (section == 1){
        headerView.title = @"发车点";
        headerView.isLine = YES;
        headerView.desc = self.currentOrigin;
        headerView.image = [UIImage imageNamed:@"mine_store"];
    }else {
        headerView.title = @"修改密码";
        headerView.isLine = YES;
        headerView.image = [UIImage imageNamed:@"register_password"];
    }
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        ZCUserInfoStoreModel *storeModel = self.userInfoModel.storehouses[indexPath.row];
        self.currentStore = storeModel.name;
        [[NSUserDefaults standardUserDefaults] setObject:storeModel.storeId forKey:UserStoreId];
        [[NSUserDefaults standardUserDefaults] setObject:storeModel.name forKey:UserStoreName];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
        ZCMineStoreTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selected = YES;
        self.storeIndex = indexPath;
        
    }else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            self.currentOrigin = @"全部";
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:UserOriginId];
        }else {
            ZCOriginLocationModel *originM = self.userInfoModel.opDeliveryPoints[indexPath.row - 1];
            self.currentOrigin = originM.name;
            [[NSUserDefaults standardUserDefaults] setObject:originM.originId forKey:UserOriginId];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
        ZCMineStoreTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selected = YES;
        self.index = indexPath;
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        ZCMineStoreTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selected = NO;
    }
}

#pragma mark - ZCMineTableHeaderViewDelegate
- (void)mineTableHeaderViewTapWithIndex:(NSInteger)index {
    if (index == 0) {
        self.spread = !self.spread;
        [self.tableView reloadData];
        [self.tableView selectRowAtIndexPath:self.storeIndex animated:YES scrollPosition:UITableViewScrollPositionNone];
        
    }else if (index == 1) {
        self.originSpread = self.userInfoModel.opDeliveryPoints.count > 0 ? !self.originSpread : self.originSpread;
        
        //崩溃  section1数据源增加item时，其实也影响到了section0。单纯刷新section1就会崩溃了
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationNone];
        [self.tableView reloadData];
        if (self.originSpread) {
            [self.tableView selectRowAtIndexPath:self.index animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
        
    }else if (index == 2) {
        ZCMineChangePasswordViewController *changePasswordVC = [[ZCMineChangePasswordViewController alloc] init];
        [self.navigationController pushViewController:changePasswordVC animated:YES];
    }
}

#pragma mark - 布局
- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top);
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.height.mas_equalTo(space(550));
    }];
    
    [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.topView.mas_top);
        make.left.equalTo(weakSelf.topView.mas_left);
        make.right.equalTo(weakSelf.topView.mas_right);
        make.height.mas_equalTo(space(470));
    }];
    
    [_headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.topView.mas_top).offset(space(124));
        make.centerX.equalTo(weakSelf.topView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(space(190), space(190)));
    }];
    
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.headerImageView.mas_bottom).offset(space(30));
        make.centerX.equalTo(weakSelf.headerImageView.mas_centerX);
        make.height.mas_equalTo(space(60));
    }];
    
    [_levelLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.nameLabel.mas_bottom).offset(space(10));
        make.centerX.equalTo(weakSelf.nameLabel.mas_centerX);
    }];
    
    [_middleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.topView.mas_bottom).offset(space(20));
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(space(-20) - 49);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.middleView.mas_top);
        make.left.equalTo(weakSelf.middleView.mas_left);
        make.right.equalTo(weakSelf.middleView.mas_right);
        make.bottom.equalTo(weakSelf.middleView.mas_bottom);
    }];
    
}

@end
